package org.spitter.util;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

public class ImageUtil {

	private String webRootPath;

	public ImageUtil() {
		webRootPath = "D:\\springsource\\workspace\\SpitterApp\\src\\main\\webapp";
	}

	@Autowired
	public void setWebRootPath(String webRootPath) {
		this.webRootPath = webRootPath;
	}

	/**
	 * Validates the type of the image
	 * 
	 * @param image
	 */
	public void validateImage(MultipartFile image) {
		String[] supportedTypes = { "image/jpeg", "image/gif", "image/png" };
		boolean valid = false;
		for (int i = 0; i < supportedTypes.length; i++) {
			if (image.getContentType().equals(supportedTypes[i])) {
				valid = true;
				break;
			}
		}
		if (!valid)
			throw new ImageUploadException(
					"Only JPG,GIF and PNG images accepted");
	}

	public void saveProfileImage(String fileName, MultipartFile image) {

		try {
			File file = new File(webRootPath + "/resources/images/avatars/"
					+ fileName);
			FileUtils.writeByteArrayToFile(file, image.getBytes());
		} catch (IOException e) {
			throw new ImageUploadException("Unable to save image");
		}
	}
}
